package com.example.musicdemo1.ui.player

import android.animation.ObjectAnimator
import android.animation.ValueAnimator
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.animation.LinearInterpolator
import android.widget.ImageButton
import android.widget.ImageView
import android.widget.SeekBar
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import com.bumptech.glide.Glide
import com.example.musicdemo1.R
import com.example.musicdemo1.service.MusicPlayer
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch

class PlayerFragment : Fragment() {
    private lateinit var songTitleText: TextView
    private lateinit var artistNameText: TextView
    private lateinit var seekBar: SeekBar
    private lateinit var currentTimeText: TextView
    private lateinit var totalTimeText: TextView
    private lateinit var playPauseButton: ImageButton
    private lateinit var coverImage: ImageView
    private lateinit var prevButton: ImageButton
    private lateinit var nextButton: ImageButton

    private val handler = Handler(Looper.getMainLooper())
    private val updateSeekBar = object : Runnable {
        override fun run() {
            updateProgress()
            handler.postDelayed(this, 1000)
        }
    }

    private var rotationAnimator: ObjectAnimator? = null
    private var currentRotation = 0f

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.fragment_player, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        
        songTitleText = view.findViewById(R.id.songTitle)
        artistNameText = view.findViewById(R.id.artistName)
        seekBar = view.findViewById(R.id.seekBar)
        currentTimeText = view.findViewById(R.id.currentTime)
        totalTimeText = view.findViewById(R.id.totalTime)
        playPauseButton = view.findViewById(R.id.playPauseButton)
        coverImage = view.findViewById(R.id.coverImage)
        prevButton = view.findViewById(R.id.prevButton)
        nextButton = view.findViewById(R.id.nextButton)

        setupViews()
        setupRotationAnimation()
        observePlaybackState()
    }

    private fun setupViews() {
        seekBar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
            override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
                if (fromUser) {
                    MusicPlayer.seekTo(progress)
                }
            }
            override fun onStartTrackingTouch(seekBar: SeekBar?) {}
            override fun onStopTrackingTouch(seekBar: SeekBar?) {}
        })

        playPauseButton.setOnClickListener {
            if (MusicPlayer.isPlaying.value) {
                MusicPlayer.pause()
            } else {
                MusicPlayer.resume()
            }
        }

        prevButton.setOnClickListener {
            MusicPlayer.playPrevious()
        }

        nextButton.setOnClickListener {
            MusicPlayer.playNext()
        }
    }

    private fun setupRotationAnimation() {
        rotationAnimator = ObjectAnimator.ofFloat(coverImage, View.ROTATION, currentRotation, currentRotation + 360f).apply {
            duration = 20000 // 20秒转一圈
            interpolator = LinearInterpolator()
            repeatCount = ValueAnimator.INFINITE
        }
    }

    private fun observePlaybackState() {
        viewLifecycleOwner.lifecycleScope.launch {
            MusicPlayer.currentMusic.collectLatest { music ->
                music?.let {
                    songTitleText.text = it.title
                    artistNameText.text = it.singer
                    Glide.with(requireContext())
                        .load(it.coverImgUrl)
                        .into(coverImage)
                    seekBar.max = MusicPlayer.getDuration()
                    totalTimeText.text = formatTime(MusicPlayer.getDuration())
                    updateProgress()
                }
            }
        }

        viewLifecycleOwner.lifecycleScope.launch {
            MusicPlayer.isPlaying.collectLatest { isPlaying ->
                playPauseButton.setImageResource(
                    if (isPlaying) R.drawable.ic_pause else R.drawable.ic_play
                )
                
                if (isPlaying) {
                    currentRotation = coverImage.rotation
                    rotationAnimator?.setFloatValues(currentRotation, currentRotation + 360f)
                    rotationAnimator?.start()
                    handler.post(updateSeekBar)
                } else {
                    rotationAnimator?.pause()
                    handler.removeCallbacks(updateSeekBar)
                    updateProgress()
                }
            }
        }
    }

    private fun updateProgress() {
        val currentPosition = MusicPlayer.getCurrentPosition()
        seekBar.progress = currentPosition
        currentTimeText.text = formatTime(currentPosition)
    }

    private fun formatTime(milliseconds: Int): String {
        val seconds = milliseconds / 1000
        val minutes = seconds / 60
        val remainingSeconds = seconds % 60
        return String.format("%02d:%02d", minutes, remainingSeconds)
    }

    override fun onDestroyView() {
        super.onDestroyView()
        rotationAnimator?.cancel()
        handler.removeCallbacks(updateSeekBar)
    }

    override fun onResume() {
        super.onResume()
        updateProgress()
    }
} 